/**
 * ThirdPartyResponseXmlParser.java
 * author: yujiakui
 * 2017年8月29日
 * 上午10:02:54
 */
package com.ctim.service.integration.parser.impl;

import java.io.Reader;

import org.xmappr.Xmappr;

import com.ctim.common.exception.PcsRunTimeException;
import com.ctim.service.integration.parser.ThirdPartyParserConfig;
import com.ctim.service.integration.parser.ThirdPartyResponseParser;

/**
 * @author yujiakui
 *
 *         上午10:02:54
 *
 *         返回结果对应的xml解析器
 */
public abstract class AbstractThirdPartyResponseXmlParser implements ThirdPartyResponseParser {

	/*
	 *
	 * @see
	 * com.ctim.service.integration.parser.ThirdPartyResponseParser#parse(java.
	 * lang.Object, java.lang.Class,
	 * com.ctim.service.integration.parser.ThirdPartyParserConfig)
	 */
	@Override
	public <T> T parse(Object inputObj, Class<T> outputClass, ThirdPartyParserConfig thirdPartyParserConfig) {

		Xmappr xm = new Xmappr();
		xm.addMapping(thirdPartyParserConfig.getMappingCfgReader());
		Reader reader = getInputObjReader(inputObj);
		T outputObj;
		try {
			outputObj = outputClass.newInstance();
		} catch (InstantiationException | IllegalAccessException ex) {
			throw new PcsRunTimeException("第三方接口对应的Class生成对象失败", ex);
		}
		xm.fromXML(reader, outputObj);

		return outputObj;
	}

	/**
	 * 获取输入对象对应的reader
	 *
	 * @param inputObj
	 * @return
	 */
	protected abstract Reader getInputObjReader(Object inputObj);

}
